package com.hospital.common.config;

import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.enums.FeignInternalCallExpCode;
import com.hospital.common.exception.FeignInternalCallException;
import com.hospital.common.utils.ThreadLocalUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

import static com.hospital.common.base.interfaces.Const.*;

/**
 * Feign拦截器配置
 * @author yhn
 * @version 1.0
 */
@Configuration
public class FeignConfig implements RequestInterceptor {
    /**
     * feign内部调用时添加以下三个请求头:
     * <br>
     * 1. USER_ID_HEADER: 用户ID
     * <br>
     * 2. ROLE_TYPE_HEADER: 角色类型
     * <br>
     * 3. INTERNAL_CALL_HEADER: 内部调用标识
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ThreadAttributes threadAttributes = ThreadLocalUtils.get();
        if(ObjectUtils.isEmpty(threadAttributes)){
            throw new FeignInternalCallException(FeignInternalCallExpCode.THREAD_ATTRIBUTES_NOT_EXIST);
        }
        requestTemplate.header(USER_ID_HEADER, String.valueOf(threadAttributes.getUserId()));
        requestTemplate.header(ROLE_TYPE_HEADER, String.valueOf(threadAttributes.getRoleType()));
        requestTemplate.header(INTERNAL_CALL_HEADER,INTERNAL_CALL_VALUE);
    }
}
